package com.cyzy.homework.repository;

import com.cyzy.homework.entity.HomeworkSubmit;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

/**
 * 作业提交Repository
 */
@Repository
public interface HomeworkSubmitRepository extends JpaRepository<HomeworkSubmit, Long> {
    
    /**
     * 根据作业ID查询提交列表
     */
    Page<HomeworkSubmit> findByHomeworkIdOrderBySubmitTimeDesc(Long homeworkId, Pageable pageable);
    
    /**
     * 根据学生ID查询提交列表
     */
    Page<HomeworkSubmit> findByUserIdOrderBySubmitTimeDesc(String userId, Pageable pageable);
    
    /**
     * 根据作业ID和学生ID查询提交记录
     */
    Optional<HomeworkSubmit> findByHomeworkIdAndUserId(Long homeworkId, String userId);
    
    /**
     * 根据作业ID和状态查询提交列表
     */
    Page<HomeworkSubmit> findByHomeworkIdAndStatusOrderBySubmitTimeDesc(Long homeworkId, Integer status, Pageable pageable);
    
    /**
     * 根据学生ID和状态查询提交列表
     */
    Page<HomeworkSubmit> findByUserIdAndStatusOrderBySubmitTimeDesc(String userId, Integer status, Pageable pageable);
    
    /**
     * 统计作业提交数量
     */
    long countByHomeworkId(Long homeworkId);
    
    /**
     * 统计作业已提交数量
     */
    long countByHomeworkIdAndStatus(Long homeworkId, Integer status);
    
    /**
     * 统计学生提交数量
     */
    long countByUserId(String userId);
    
    /**
     * 统计学生已提交数量
     */
    long countByUserIdAndStatus(String userId, Integer status);
    
    /**
     * 查询未批改的提交
     */
    @Query("SELECT hs FROM HomeworkSubmit hs WHERE hs.homeworkId = :homeworkId AND hs.status = 1")
    List<HomeworkSubmit> findUnGradedSubmits(@Param("homeworkId") Long homeworkId);
    
    /**
     * 查询已批改的提交
     */
    @Query("SELECT hs FROM HomeworkSubmit hs WHERE hs.homeworkId = :homeworkId AND hs.status = 2")
    List<HomeworkSubmit> findGradedSubmits(@Param("homeworkId") Long homeworkId);
    
    /**
     * 根据作业ID查询所有提交（不分页）
     */
    List<HomeworkSubmit> findByHomeworkIdOrderBySubmitTimeDesc(Long homeworkId);
    
    /**
     * 根据学生ID和作业ID列表查询提交
     */
    @Query("SELECT hs FROM HomeworkSubmit hs WHERE hs.userId = :userId AND hs.homeworkId IN :homeworkIds")
    List<HomeworkSubmit> findByUserIdAndHomeworkIdIn(@Param("userId") String userId, @Param("homeworkIds") List<Long> homeworkIds);
}

